/* ----------------------------------------------------------------------
*
* Copyright (C) 2025 XiaoFei. All rights reserved.
*
* @file:		XiaoZhi_DHT11.c
* @author:		XiaoFei
* @Date:     	17-January-2025
* @Revision: 	V1
* @Project: 	XiaoFei BSP Library
*
* -------------------------------------------------------------------- */

#include "stm32f10x.h"          
#include "XiaoFei_Delay.h"
#include "XiaoZhi_DHT11.h"

/* 
* @function: 	DHT11_ReadByte
* @return:		The byte read from DHT11 device.
*/
static unsigned char DHT11_ReadByte(void)
{
	static unsigned char ucharcomdata;
	for(unsigned char i=0;i<8;i++)    
	{
		while(!DHT11_DQRead);
		XiaoFei_Delay_us(40);
		if(DHT11_DQRead) 
		{
			while(DHT11_DQRead);
			ucharcomdata|=(unsigned char)(0x01<<(7-i));
		}	
		else
			ucharcomdata&=(unsigned char)(~(0x01<<(7-i)));
	}
	return ucharcomdata;
}

/* 
* @function: 	DHT11_GetData
* @parameter:	[out] DHT11				    The data from DHT11 device.
* @return:		Successes or failures of the data get from DHT11 device.
*/
unsigned char DHT11_GetData(DHT11_TypeDef* DHT11)
{
	RCC_APB2PeriphClockCmd(RCC_GPIO_DHT11,ENABLE);		
	GPIO_InitTypeDef GPIO_InitStructure;
	GPIO_InitStructure.GPIO_Pin = DHT11_DQ_Pin;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_Init(DHT11_DQ_GPIO, &GPIO_InitStructure);
    DHT11_DQ(0);
	XiaoFei_Delay_ms(18);
    DHT11_DQ(1);
	XiaoFei_Delay_us(30);
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
	GPIO_Init(DHT11_DQ_GPIO, &GPIO_InitStructure);
	if(!DHT11_DQRead)
	{
		while(!DHT11_DQRead);
		while(DHT11_DQRead);
		DHT11->humi_H=DHT11_ReadByte();
		DHT11->humi_L=DHT11_ReadByte();
		DHT11->Temp_H=DHT11_ReadByte();
		DHT11->Temp_L=DHT11_ReadByte();
		DHT11->Chack=DHT11_ReadByte();
		GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
		GPIO_Init(DHT11_DQ_GPIO, &GPIO_InitStructure);
		DHT11_DQ(1);
		if(DHT11->humi_H+DHT11->humi_L+DHT11->Temp_H+DHT11->Temp_L==DHT11->Chack)
		{
			DHT11->Temp=(int)DHT11->Temp_H+(int)DHT11->Temp_L*(float)0.1;
			DHT11->Humi=(int)DHT11->humi_H+(int)DHT11->humi_L*(float)0.1;
			return 0x01;
		}
		else 
			return 0x00;
	}
	else
	{
		DHT11->Temp=0;
		DHT11->Humi=0;
		return 0x00;
	}
}




